package com.lagou.edu.factory;

import com.lagou.edu.utils.TransactionManger;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理工厂
 * 生成代理对象
 */
public class ProxyFactory {

    //创建对象交给Ioc容器
    private TransactionManger transactionManger;

    public void setTransactionManger(TransactionManger transactionManger) {
        this.transactionManger = transactionManger;
    }

    /*
    //构造函数私有化
    private ProxyFactory() {
    }

    //初始化
    private static ProxyFactory proxyFactory = new ProxyFactory();

    //对外提供获取实例化对象的接口
    public static ProxyFactory getInstance() {
        return proxyFactory;
    }*/

    /**
     * jdk动态代理
     *
     * @param object
     * @return
     */
    public Object getJdkProxy(Object object) {
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                Object result = null;
                try {
                    //1. 关闭事务自动提交,也就是开启事务
                    transactionManger.closeAutoCommit();

                    //执行原方法,可能方法有返回值
                    result = method.invoke(object, objects);

                    //2. 提交事务
                    transactionManger.commit();
                } catch (Exception e) {
                    //打印日志
                    e.printStackTrace();
                    //3. 回滚事务
                    transactionManger.rollback();
                    //将异常抛出,以便上层知道出现什么错误
                    throw e;
                }
                return result;
            }
        });
    }

    /**
     * cglib动态代理
     *
     * @param object
     * @return
     */
    public Object getCglibProxy(Object object) {
        return Enhancer.create(object.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try {
                    //1. 关闭事务自动提交,也就是开启事务
                    transactionManger.closeAutoCommit();

                    //执行原方法,可能方法有返回值
                    result = method.invoke(object, objects);

                    //2. 提交事务
                    transactionManger.commit();
                } catch (Exception e) {
                    //打印日志
                    e.printStackTrace();
                    //3. 回滚事务
                    transactionManger.rollback();
                    //将异常抛出,以便上层知道出现什么错误
                    throw e;
                }
                return result;
            }
        });
    }
}
